package library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

import struct.CompanyInfo;


public class JsonParser extends Thread {
	
	
	JSONObject result;
	ActionClass actionClass;
	String url;
	
	public JsonParser(String url, ActionClass actionclas) {
		// TODO Auto-generated constructor stub
		this.url = url;
		this.actionClass = actionclas; 	
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		connect(url);
		mHandler.sendEmptyMessage(0);
		
	}
	
	Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			actionClass.actionSuccess(result);
		}
	};
	
	private void connect(String url){

		// Create the httpclient
		HttpClient httpclient = new DefaultHttpClient();

		// Prepare a request object
		HttpGet httpget = new HttpGet(url);

		// Execute the request
		String returnString;
		
		HttpResponse response;

		try {

			// Open the webpage.
			response = httpclient.execute(httpget);

			if(response.getStatusLine().getStatusCode() == 200){
				// Connection was established. Get the content.

				HttpEntity entity = response.getEntity();
				// If the response does not enclose an entity, there is no need
				// to worry about connection release

				if (entity != null) {
					// A Simple JSON Response Read
					InputStream instream = entity.getContent();

					// Load the requested page converted to a string into a JSONObject.
					result = new JSONObject(convertStreamToString(instream));
					

					// Make array of the suggestions
					
					// Cose the stream.
					instream.close();
				}
			}
			else {
				// code here for a response othet than 200.  A response 200 means the webpage was ok
				// Other codes include 404 - not found, 301 - redirect etc...
				// Display the response line.
				returnString = "Unable to load page - " + response.getStatusLine();
				actionClass.actionFailed();
			}
		}
		catch (IOException  ex) {
			// thrown by line 80 - getContent();
			// Connection was not established
			returnString = "Connection failed; " + ex.getMessage();
			actionClass.actionFailed();

		}
		catch (JSONException ex){
			// JSON errors
			returnString = "JSON failed; " + ex.getMessage();
			actionClass.actionFailed();

		}
	}

	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
